<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml" lang="zh">

<head>
    <th:block th:include="common/head::head"/>
    <style>
        .div-project {
            width: 100%;
            margin: 30px 0;
        }

        .div-project .layui-inline {
            width: calc(50% - 5px);
            margin-right: 0px;
        }
    </style>
</head>

<body>
<div class="layui-container div-project" id="div-project">
    <form action="save_project" method="post" class="layui-form" id="form_project" lay-filter="form_project">

        <div class="layui-form-item" th:unless="${item}">
            <blockquote class="layui-elem-quote layui-quote-nm">
                创建分发项目是在不同的节点新创建对应项目（项目路径为节点白名单中的值，然后所有节点都将自动配置对应的白名单）,项目id、项目名称和分发id、分发名称同步
            </blockquote>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label"><span class="x-red">*</span>项目ID</label>
                <div class="layui-input-block">
                    <input type="text" name="id" placeholder="程序运行标志（设置后将不能修改）" required lay-verify="required"
                           th:class="${item}?'layui-input  layui-disabled':'layui-input'" th:value="${item?.id}"
                           th:readonly="${item}">
                    <input type="hidden" name="reqId" th:value="${reqId}">
                    <input type="hidden" name="type" th:value="${type}">
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label"><span class="x-red">*</span>项目名称</label>
                <div class="layui-input-block">
                    <input type="text" name="name" placeholder="项目名称" required lay-verify="required"
                           class="layui-input" th:value="${item?.name}">
                    <div class="layui-hide">
                        <input type="checkbox" name="edit" th:checked="${item}">
                    </div>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label"><span class="x-red">*</span>运行方式</label>
                <div class="layui-input-block">
                    <select name="runMode" lay-filter="runMode">
                        <option th:each="itemPath : ${runModes}" th:value="${itemPath}" th:text="${itemPath}">
                        </option>
                    </select>
                </div>
            </div>
            <div class="layui-inline" th:style="${item!=null}?'display: none;':''"
                 id="mainClassDiv">
                <label class="layui-form-label">MainClass</label>
                <div class="layui-input-block">
                    <input type="text" name="mainClass" placeholder="程序运行的 main 类(jar模式运行可以不填)" class="layui-input">
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label"><span class="x-red">*</span>项目路径</label>
                <div class="layui-input-block">
                    <select name="whitelistDirectory" required lay-verify="required" lay-filter="whitelistDirectory">、
                        <th:block th:unless="${#lists.isEmpty(whitelistDirectory)}">
                            <option value="">请选择白名单</option>
                            <option th:value="${itemPath}"
                                    th:each="itemPath : ${whitelistDirectory}"
                                    th:text="${itemPath}"></option>
                        </th:block>
                        <option value="" th:if="${#lists.isEmpty(whitelistDirectory)}">请配置白名单</option>
                    </select>
                </div>
            </div>
            <div class="layui-inline">
                <label class="layui-form-label"><span class="x-red">*</span>项目Jar包</label>
                <div class="layui-input-block">
                    <input type="text" name="lib" placeholder="jar存储的文件夹" required lay-verify="required"
                           class="layui-input">
                </div>
            </div>

            <div class="layui-form-mid layui-word-aux" style="padding: 0 !important;">
                <div class="layui-input-block" style="color: red;min-height: 0px;">
                    结果：
                    <span id="projectStart">请选择</span>
                    <span id="projectEnd" style="margin-left: -4px">请填写</span>
                    <span>日志路径：</span>
                </div>
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">分发后</label>
                <div class="layui-input-block">
                    <select name="afterOpt" id="afterOpt">
                        <option value="">请选择分发后的操作</option>
                        <option th:each="sel : ${afterOpt}" th:value="${sel.code}"
                                th:selected="${sel.code==item?.afterOpt}" th:text="${sel.desc}">
                        </option>
                    </select>
                </div>
            </div>
        </div>

        <div class="layui-collapse" style="display: none;" id="nodeListDiv">
        </div>
        <div class="layui-form-item" style="padding-left: 30%;margin-top: 20px;" id="appendNodeDiv">
            <a class="layui-btn layui-btn-sm layui-btn-warm" id="add_selectNode">添加节点项目
            </a>
        </div>

        <div class="layui-form-item" style="padding-left: 20%;">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="submitProject" id="project_submit">提交
            </button>
            <a th:if="${item}" class="layui-btn layui-btn-warm" th:data-id="${item.id}" id="delete_project">删除</a>
        </div>
    </form>
</div>

<div id="selectNode" style="display: none;padding-top: 20px;">
    <form action="" class="layui-form" lay-filter="form_node">
        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">选择节点</label>
                <div class="layui-input-block">
                    <select name="nodeId" required lay-verify="required" lay-filter="selectNode">
                        <option value="">请选择节点</option>

                        <option th:each="i : ${nodeModels}" th:value="${i.id}" th:nodeName="${i.name}"
                                th:text="${i.name}"></option>
                    </select>
                </div>
            </div>
        </div>
        <div class="layui-form-item">
            <div class="layui-inline">
                <div class="layui-input-block">
                    <button class="layui-btn layui-btn-normal" lay-submit lay-filter="submitNode">确定
                    </button>
                </div>
            </div>
        </div>
    </form>
</div>
</body>
<script id="nodePar" type="text/html">
    <div class="layui-colla-item" nodeDiv="{{ d.nodeId }}">
        <div class="layui-colla-title">
            <input type="hidden" name="add_{{ d.nodeId }}" value="{{= d.nodeId }}">
            <div>
                {{ d.nodeName }}
            </div>

            <div class="layui-layout-right" style="padding-right: 10%;">

                <button op="del_node"
                        class="layui-btn layui-btn-sm layui-btn-warm">
                    <i class="layui-icon">&#xe640;</i>
                    删除
                </button>
            </div>
        </div>
        <div class="layui-colla-content  {{# if(!d.edit){  }} layui-show  {{# } }}">
            <div class="layui-form-item">
                <div class="layui-form-mid layui-word-aux" style="padding: 0 !important;">
                    <div class="layui-input-block" id="tipMsgDiv_{{ d.nodeId }}"
                         style="color: red;min-height: 0px;display: none">
                        提示：<span id="tipMsg_{{ d.nodeId }}"></span>
                    </div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">WebHooks</label>
                <div class="layui-input-block">
                    <input type="text" name="{{ d.nodeId }}_token" placeholder="关闭程序时自动请求,非必填" class="layui-input"
                           value="{{= d.token }}">
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">Jvm参数</label>
                    <div class="layui-input-block">
                    <textarea name="{{ d.nodeId }}_jvm" placeholder="jvm参数,非必填.如：-Xmin=512m -Xmax=512m"
                              class="layui-textarea">{{= d.jvm }}</textarea>
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">args参数</label>
                    <div class="layui-input-block">
                    <textarea name="{{ d.nodeId }}_args" placeholder="Main函数args参数,非必填.如：--service.port=8080"
                              class="layui-textarea">{{= d.args }}</textarea>
                    </div>
                </div>
            </div>
        </div>
    </div>
</script>

<script type="text/javascript" th:inline="javascript"
        th:each="nodeP,iterStat : ${item?.outGivingNodeProjectList}">
    findFirst = false;
    asyncFn.push(function () {
        loadingAjax({
            url: '../node/manage/getProjectData.json',
            data: {
                id: [[${nodeP.projectId}]],
                nodeId: [[${nodeP.nodeId}]]
            },
            success: function (data) {
                if (200 === data.code) {
                    var getProjectInfo = data.data;
                    if (data.data) {
                        var nodeId = [[${nodeP.nodeId}]];
                        var selectOption = $('select[name="nodeId"] option[value="' + nodeId + '"]');
                        getProjectInfo["nodeId"] = nodeId;
                        getProjectInfo["edit"] = true;
                        addNode(getProjectInfo, selectOption);
                        //
                        if (!findFirst) {
                            form.val("form_project", {
                                runMode: getProjectInfo.runMode,
                                lib: getProjectInfo.lib,
                                mainClass: getProjectInfo.mainClass,
                                whitelistDirectory: getProjectInfo.whitelistDirectory
                            });
                            $("#projectEnd").text(getProjectInfo.lib);
                            $("#projectStart").text(getProjectInfo.whitelistDirectory);
                            if (getProjectInfo.runMode === 'ClassPath') {
                                $("#mainClassDiv").show();
                            }
                            findFirst = true;
                        }
                        form.render();
                    } else {
                        layer.alert([[${nodeP.nodeId}]] + "节点未拉取到对应项目,不建议此次进行保存操作,以防止数据丢失");
                    }
                } else {
                    layer.alert([[${nodeP.nodeId}]] + "节点未拉取到对应项目,不建议此次进行保存操作,以防止数据丢失:" + data.msg);
                }
            },
            error: function () {
                layer.alert("节点未拉取到对应项目,不建议此次进行保存操作,以防止数据丢失");
            }
        });
    });
</script>
<script type="text/javascript">

    var laytpl;
    var whitelistDirectorySelect;

    function loadSuccess() {
        // var tipMsgDiv = ("#tipMsgDiv");
        // 提交项目表单
        form.on('submit(submitProject)', function (data) {
            if ($("div[nodeDiv]").length < 2) {
                layer.msg("节点分发至少需要两个项目及以上");
                return false;
            }
            loadingAjax({
                url: data.form.action,
                data: data.field,
                success: function (data) {
                    layer.msg(data.msg);
                    if (200 == data.code) {
                        closeTab();
                    }
                }
            });
            return false;
        });

        form.on('select(runMode)', function (data) {
            let val = data.value;
            if (val === "ClassPath") {
                $("#mainClassDiv").show();
            } else {
                $("#mainClassDiv").hide();
            }
        });


        form.on('select(whitelistDirectory)', function (data) {
            let val = data.value;
            if (val === "") {
                val = "请选择";
                // tipMsgDiv.hide();
                // tipMsgDiv.attr("msg", "请填写项目路径")
            }
            $("#projectStart").text(val);
            if (val !== "") {
                checngeLib();
            }

        });
        $("input[name='lib']").change(function (e) {
            let val = $(this).val();
            if (val === "") {
                val = "请填写";
                // tipMsgDiv.hide();
                // tipMsgDiv.attr("msg", "请填写项目的jar路径")
            }
            $("#projectEnd").text(val);
            if (val !== "") {
                checngeLib();
            }
        });
        whitelistDirectorySelect = $("select[name='whitelistDirectory']");

        $("#add_selectNode").click(function () {
            layerOpen({
                type: 1,
                title: '选择节点',
                content: $('#selectNode'),
                area: ['40%', '60%']
            });
        });

        layui.use(['laytpl'], function () {
            laytpl = layui.laytpl;
            //
            form.on('submit(submitNode)', function (data) {
                var nodeId = data.field.nodeId;
                if (nodeId == "") {
                    layer.msg("请选择节点");
                    return false;
                }
                //
                var selectOption = $("select[name='nodeId']").find("option:selected");
                var nodeName = selectOption.attr("nodeName");
                addNode({
                    nodeName: nodeName,
                    nodeId: nodeId
                }, selectOption);
                return false;
            });

            $("body").delegate("button[op='del_node']", "click", function (e) {
                layui.stope(e);
                var par = $(this).parent().parent().parent();
                var nodeId = par.attr("nodeDiv");
                layer.confirm('确定删除此节点项目吗【 ' + nodeId + '】？（保存后将自动删除对应节点的项目）', {
                    title: '系统提示'
                }, function (index) {
                    layer.close(index);

                    $("select[name='nodeId'] option[value='" + nodeId + "']").attr("disabled", false);
                    form.render();
                    $("#add_selectNode").show();
                    par.remove();

                    if ($("div[nodeDiv]").length <= 0) {
                        $("#nodeListDiv").hide();
                    }
                });
                return false;
            });
        });


        $("#delete_project").click(function () {
            var id = $(this).attr("data-id");
            var msg = '确定删除分发项目【 ' + id + '】？（会自动删除节点下的对应项目请谨慎操作）';
            layer.confirm(msg, {
                title: '系统提示'
            }, function (index) {
                loadingAjax({
                    url: './delete_project.json',
                    data: {
                        id: id
                    },
                    success: function (data) {
                        layer.msg(data.msg);
                        if (200 == data.code) {
                            closeTab();
                        }
                    }
                });
            });
        });
    }

    function checngeLib() {
        var wVal = whitelistDirectorySelect.val();
        if (wVal == "") {
            layer.msg("请选择白名单");
            return;
        }
        var lib = wVal + $("#projectEnd").text();
        $("div[nodeDiv]").each(function () {
            var nodeId = $(this).attr("nodeDiv");
            silentAjax({
                url: '../node/manage/judge_lib.json',
                data: {
                    id: "[[${item?.id}]]",
                    nodeId: nodeId,
                    newLib: lib
                },
                success: function (data) {
                    if (200 == data.code) {
                        $("#tipMsgDiv_" + nodeId).hide();
                    } else {
                        $("#tipMsg_" + nodeId).text(data.msg).parent().show();
                    }
                }
            });
        });
    }

    function closeTab() {
        try {
            top.frames["outgiving"].location.reload();
        } catch (e) {
        }
        setTimeout(function () {
            var element = top.layui.element;
            var id = self.frameElement.getAttribute('id');
            element.tabDelete('mainTabs', id);
            element.tabChange('mainTabs', "tab_outgiving节点分发");
        }, 1500);
    }

    function addNode(data, selectOption) {
        var html = document.getElementById("nodePar");
        var nodeName = selectOption.attr("nodeName");
        if (!data.nodeName) {
            data.nodeName = nodeName;
        }
        laytpl(html.innerHTML).render(data, function (newHtml) {
            $("#nodeListDiv").append(newHtml).show();
            layer.closeAll("page");
            // 改变已经选过的选项
            selectOption.attr("disabled", true);
            selectOption.attr("selected", false)
            form.render();
            element.render();
            // 检查按钮状态
            if ($("div[nodeDiv]").length >= $("select[name='nodeId']").find("option").length - 1) {
                $("#add_selectNode").hide();
            }
        });
    }
</script>
</html>